#ifndef _THREADMGR_HPP_
#define	_THREADMGR_HPP_

/*******************************************************************************
 ** Name: ThreadMgr.hpp                                                       **
 ** Description:                                                              **
 **                                                                           **
 ** Open Source Initiative (OSI) Approved License                             **
 **                                                                           **
 **  Copyright (c) 2009-2010 Barry "Gian" James  <bjames@munixos.net>         **
 **  All rights reserved.                                                     **
 **                                                                           **
 **  Redistribution and use in source and binary forms, with or without       **
 **  modification, are permitted provided that the following conditions are   **
 **  met:                                                                     **
 **                                                                           **
 **  * Redistributions of source code must retain the above copyright notice, **
 **    this list of conditions and the following disclaimer.                  **
 **  * Redistributions in binary form must reproduce the above copyright      **
 **    notice, this list of conditions and the following disclaimer in the    **
 **    documentation and/or other materials provided with the distribution.   **
 **                                                                           **
 **  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS      **
 ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED **
 ** TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A           **
 ** PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT        **
 ** HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,    **
 ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED  **
 ** TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR    **
 ** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF    **
 ** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING      **
 ** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS        **
 ** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.              **
 **                                                                           **
 ******************************************************************************/
// Created on March 24, 2010, 3:21 AM
// Modified $Date$ by $Author$

#define ThreadMgr_hpp_ID   "$Id$"

#include <queue>
#include <pthread.h>

typedef void * (*tfunc)(void *);	// Worker func()
typedef void * (*ffunc)(void *);	// Finalize func()

class CriticalSection
{
public:
	CriticalSection();
	~CriticalSection();

	bool	Enter();
	bool	Leave();
	bool	IsValid() { return bIsValid; }

private:
	typedef pthread_mutex_t * CriticalSectionType;
	CriticalSectionType	criticalSection;
	bool				bIsValid;
};


struct ThreadPoolBlock
{
    tfunc   func;
    void *  arg;
};

enum class ThreadStatus {
	All, Unassigned, Stopped, Running, RunningRequest, UnassignedRequest,
	TerminateRequest,
	max
};

// The main ideas and some code taken from pthreads from O'Reilly.
//! Manages the server's thread pool
class ThreadMgr
{
public:
    ThreadMgr(int);
    ThreadMgr(const ThreadMgr& orig) = delete;
    ~ThreadMgr();

    bool    Init();
    int     AssignWork(tfunc, void*);
    bool    QueueIsEmpty() { return msgQueue.empty(); }
    int     MaxThreads() const { return maxThreads; }

    ThreadPoolBlock * NextMsg() { ThreadPoolBlock * ret = msgQueue.front(); msgQueue.pop(); return ret; }
    pthread_mutex_t * QueueMutex() { return &lockQueue; }
    pthread_cond_t  * QueueNotEmptyCond() { return &condQueueNotEmpty; }
    static pthread_mutex_t & ReadSetMutex() { return readSetMutex; }
    static pthread_mutex_t & WriteSetMutex() { return writeSetMutex; }

    static int  _assignID() { return ++idx; }

	static void yield() { sched_yield(); }
	static void sleep(int ms) { assert(ms > 0); usleep(ms * 1000); }

	virtual bool StartThread(int id);
	virtual bool StopThread(int id);

	// thread-safe functions
	int			ThreadPoolSize() const { return maxThreads; }
	void *		GetLocalData() const;
	bool		IsPrimaryThread() const;
	int			GetAndResetThreadCalls(int id);	

	typedef struct
	{
		int 			id;
		ThreadStatus	status;
		tfunc			workFunc;
		ffunc			finalFunc;
		pthread_t		thread;
		CriticalSection* criticalSection;
		void *			localData;
	} ThreadInfo;

private:
    int     maxThreads;
    static int idx;
    bool	bInitialized;
    int		currThreadPoolSize;
    void *	primaryThreadLocalData;
    pthread_key_t localDataKey;
    CriticalSection internalCritSection;

    pthread_t *         threads;
    
    pthread_mutex_t     lockQueue;
    pthread_cond_t      condQueueNotEmpty;

    static pthread_mutex_t     readSetMutex;
    static pthread_mutex_t     writeSetMutex;
	static const pthread_key_t	invalidLocalDataKey;
	static const pthread_t		invalidThread;
	static CriticalSection		singletonCritSection;
	
	void		cleanup(bool waitForThreadTermination);
	
	void		LockThread(int id);
	void		UnlockThread(int id);

	int			GetThreadStatus(int id) const;
	void		AssocLocalDataWithThread(int id);
	void *		GetLocalDataRaw() const;
	void		CallWorkFuncForThread(int id);
	void		CallFinalizeFuncForThread(int id);
	void		CallbackHandleStatus(int id, ThreadStatus s);
 
    std::queue<ThreadPoolBlock *>    msgQueue;


};

#endif	/* _THREADMGR_HPP_ */

